var username=getCookie("username")
var into1=document.querySelector('.into1  a')
var into=document.querySelector('.into1 ')
var into2=document.querySelector('.into2  a')
var loginPrompt=document.querySelector('.login-prompt')
var login =document.querySelector('.login')
if(username){
    loginPrompt.style.display="none"
    into.style.marginLeft='265px'
    into2.innerHTML=` <a href="javascript:;" class="logout">退出</a>`
    into1.innerHTML=`<a href="javascript:;" style="color:red;">${username}</a>`
    into2.querySelector('a.logout').onclick = function(){
        if(!confirm('你确定要离开吗？')){
            return false
        }
        removeCookie('username')
        loginPrompt.style.display="block"
        into.style.marginLeft='350px'
        into1.innerHTML=`<a href="login.html">登录</a>`
        into2.innerHTML = `<a href="register.html">注册</a>`
    }
}


login.onclick=function() { //判断是否登录
    let username=getCookie('username')
    if(!username){
        layer.msg('请先登陆',{
            icon:2,
            time:1000
        },function() {
            localStorage.setItem('url',location.href)
            location.href='login.html'
        })
    }

}

var cat=document.querySelector('.sc-empty')
var center=document.querySelector('.container')
var data=localStorage.getItem('data')
if(!data ){ //判断本地存储没有数据
    
    center.style.display='none'
    cat.style.display='block'

}else{ //判断本地存储有数据
    if(data=='[]'){
        center.style.display='none'
        cat.style.display='block'
    }else{
        center.style.display='block'
        cat.style.display='none'
       init()
        selectAll()
        selectOne()
        add()
        reduce()
        total()
        delCart()
    }    
}

function init(){ //把本地存储数据渲染上页面
    var arr=JSON.parse(data)
    console.log(arr)
    let str='';
    arr.forEach(v => {
        str+=`<tr>
        <td><input type="checkbox" checked name="selectOne"></td>
        <td >${v.nameID}</td>
        <td><img src="${v.imgID}" width="80px" height="80px">
        </td>
        <td style="width:100px">￥<span class="price">${v.prince}</span>
        </td>
        <td class="number">
            <input type="button" name="reduce" value="-">
            <input type="number" name="number" value="${v.Number}">
            <input type="button" name="add" value="+">
        </td>
        <td class="xiaoji">￥<span class="subtotal"> ${v.Number*v.prince}</span></td>
        <td index=${v.id}>
            <input type="button" value="删除"  class="btn btn-danger delCart">
        </td>
    </tr>`
    });
    document.querySelector('table tbody').innerHTML=str
}

function delCart() { //删除购物车商品
    $('.delCart').click(function(){
        layer.confirm('确定删除此商品', {
            btn: ['确定','取消'] //按钮
          }, ()=>{
            $(this).parent().parent().remove();
            var arr =JSON.parse(data)
            var index =arr.findIndex(v=>v.id==$(this).parent().attr('index'))
            arr.splice(index,1)
            localStorage.setItem('data',JSON.stringify(arr))
            total()
            location.reload()
            layer.msg('删除成功', {icon: 1,time:2000});
          }) ; 
    })
}
 
function subtotal(){ //计算小计
    $('[name="number"]').each(function(i,numberInput){
        let number = $(numberInput).val()
        let price = $(numberInput).parent().prev().find('span.price').text()
        let sub = number * price;
        $(numberInput).parent().next().find('span.subtotal').text(sub)
    })

}

function total() { //总数计算
    var totalNumber = 0 //商品总数量
    var totalPrice = 0 //商品总价格
    $('[name="selectOne"]:checked').each(function(i,checkbox){
        let number=$(checkbox).parent().siblings('.number').find('[name="number"]').val()-0
        totalNumber +=number
        let xiaoji=$(checkbox).parent().siblings('.xiaoji').find('span.subtotal').text()-0
        totalPrice +=xiaoji
    })
    $('.totalNumber').text(totalNumber)
    $('.totalPrice').text(totalPrice)

}
function add(){ //数量加事件
    $('[name="add"]').click(function(){
        var number=$(this).prev().val()-0
        number++
        $(this).prev().val(number)
        var data=localStorage.getItem('data')
        var arr =JSON.parse(data)
        console.log(arr)
        var info = arr.find(v=>v.id==$(this).parent().next().next().attr('index'))
        info.Number=$(this).prev().val();
        localStorage.setItem('data',JSON.stringify(arr))
        subtotal()
        total()
    })
}
function reduce(){ //数量减事件
    $('[name="reduce"]').click(function(){
        var number=$(this).next().val()-0
        number--
        if(number<=1){
            number=1
        }
        $(this).next().val(number)
        var data=localStorage.getItem('data')
        var arr =JSON.parse(data)
        console.log(arr)
        var info = arr.find(v=>v.id==$(this).parent().next().next().attr('index'))
        info.Number=$(this).next().val();
        localStorage.setItem('data',JSON.stringify(arr))
        subtotal()
        total()
    })
}
function selectOne() { //单选事件
    $('[name="selectOne"]').click(function(){
        var arr=Array.prototype.slice.call($('[name="selectOne"]'))
        var bool=arr.every(checkbox=>checkbox.checked)
        $('[name="selectAll"]').prop('checked',bool)
        total()
    })
}

function selectAll() { //全选事件
    $('[name="selectAll"]').click(function(){
        $('[name="selectOne"]').prop('checked',$(this).prop('checked'))
        $('[name="selectAll"]').prop('checked',$(this).prop('checked'))
        total()
    })
}